<?php
namespace app\home\controller;

use app\common\logic\HelpGet;
use app\common\logic\UserWallet;
use app\common\component\help_get\HelpGetService;
use app\common\component\user\UserService;
use app\common\component\user_wallet\UserWalletService;
use app\common\component\user_wallet_log\UserWalletLogModel;
use app\common\component\user_wallet_log\UserWalletLogService;
use app\common\component\help_appointment\HelpAppointmentService;

class Withdraw extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();
	}

    public function index() {
    	$resultUserWallet = (new UserWalletService) -> getUserWallet();
    	$this -> view -> assign('user_wallet', $resultUserWallet['data']['user_wallet']);

		$resultHelpGet = (new HelpGetService()) -> getHelpGets();
		$this -> view -> assign('help_gets', $resultHelpGet);

    	return $this -> view -> fetch();
    }

    public function withdraw() {
    	if($this -> request -> isPost()) {
    		$this -> create();
    	}

		$currentTime = time();
		$WITHDRAW_TIME_STARTS = explode('.',getParam('WITHDRAW_TIME_START'));
		$WITHDRAW_TIME_START_H = $WITHDRAW_TIME_STARTS[0];
		$WITHDRAW_TIME_START_I = isset($WITHDRAW_TIME_STARTS[1])?$WITHDRAW_TIME_STARTS[1]:00;
		$WITHDRAW_TIME_START_S = strtotime($WITHDRAW_TIME_START_H. ':' . $WITHDRAW_TIME_START_I);

		$WITHDRAW_TIME_ENDS = explode('.',getParam('WITHDRAW_TIME_END'));
		$WITHDRAW_TIME_END_H = $WITHDRAW_TIME_ENDS[0];
		$WITHDRAW_TIME_END_I = isset($WITHDRAW_TIME_ENDS[1])?$WITHDRAW_TIME_ENDS[1]:'00';
		$WITHDRAW_TIME_END_S = strtotime($WITHDRAW_TIME_END_H. ':' . $WITHDRAW_TIME_END_I);

		if(($currentTime < $WITHDRAW_TIME_START_S) || ($currentTime > $WITHDRAW_TIME_END_S)) {
			echo '<meta charset="utf-8"><script>alert("不在' . 
				$WITHDRAW_TIME_START_H . '点' . $WITHDRAW_TIME_START_I .'分 ~ ' .
				$WITHDRAW_TIME_END_H . '点' . $WITHDRAW_TIME_END_I .
				'分的提现时间内!");window.history.go(-1);</script>';exit;
		}

    	$resultUser = (new UserService) -> getUser();
    	$this -> view -> assign('user', $resultUser['data']['user']);

    	$resultUserWallet = (new UserWalletService) -> getUserWallet();
    	$this -> view -> assign('user_wallet', $resultUserWallet['data']['user_wallet']);

		$this -> view -> assign('WITHDRAW_EVERYDAY_NUM', abs($this -> getWithdrawWN() - getParam('WITHDRAW_EVERYDAY_NUM')));

    	return $this -> view -> fetch();
    }

	public function getWithdrawWN() {
		return \app\common\component\help_get\HelpGetModel::where('status in(0,1,2,4) AND create_time >= ' . strtotime('00:00:00') . ' AND user_id = ' . \think\Session::get('user_id')) -> order('help_to_id DESC') -> count();
	}

    public function create() {
    	$post = $this -> request -> post();

		if($this -> validate($post, ['money' => 'require|token']) !== true) {
			echo '<meta charset="utf-8"><script>alert("请勿重复提交!");window.location.href="/withdraw";</script>';exit;
		}
		unset($post['__token__']);

		if(($post['money'] % 10) != 0) {
			echo '<meta charset="utf-8"><script>alert("提现的金额以10倍起提!");window.history.go(-1);</script>';exit;
		}

		if($post['money'] < getParam('MONEY_MIN')) {
			echo '<meta charset="utf-8"><script>alert("您提现的' . $post['money'] . '金额小于每笔金额!");window.history.go(-1);</script>';exit;
		}

		if($post['money'] > getParam('MONEY_MAX')) {
			echo '<meta charset="utf-8"><script>alert("您提现的' . $post['money'] . '金额大于每笔金额!");window.history.go(-1);</script>';exit;
		}

		$resultUserWallet = (new UserWalletService) -> getUserWallet();
    	if($post['money'] > $resultUserWallet['data']['user_wallet'] -> withdraw_position) {
    		echo '<meta charset="utf-8"><script>alert("您提现的' . $post['money'] . '金额大于你可提现金额!");window.history.go(-1);</script>';exit;
    	}
		if($post['money'] > $resultUserWallet['data']['user_wallet'] -> money) {
    		echo '<meta charset="utf-8"><script>alert("您的金钱不足,请充值!");window.history.go(-1);</script>';exit;
    	}

		if($this -> getWithdrawWN() >= getParam('WITHDRAW_EVERYDAY_NUM')) {
			echo '<meta charset="utf-8"><script>alert("您提现的次数大于可以提现的次数!");window.history.go(-1);</script>';exit;
		}

		if(getParam('APPOINTMENT_WITHDRAW_IS_OPEN') == 1) {
			$resultHelpTo = \app\common\component\help_to\HelpToModel::where('status = 4 AND begin_time >= ' . strtotime('-' . getParam('APPOINTMENT_WITHDRAW_TIME') . ' hours') . ' AND user_id = ' . \think\Session::get('user_id')) -> find();
			if(!$resultHelpTo) {
				$resultHelpAppointment = (new HelpAppointmentService()) -> getHelpAppointment();
				if($resultHelpAppointment['code'] == 0) {
					if($resultHelpAppointment['data']['help_appointment'] -> to_num <= 0) {
						echo '<meta charset="utf-8"><script>alert("请等待匹配并完成打款后，才可提现!");window.location.href="/appointment";</script>';exit;
					} else {
						echo '<meta charset="utf-8"><script>alert("请完成打款后，才可提现!");window.location.href="/farming";</script>';exit;
					}
				} else {
					echo '<meta charset="utf-8"><script>alert("请今天先预约，才可提现!");window.location.href="/appointment";</script>';exit;
				}
			}
		} else {
			$resultHelpAppointment = (new HelpAppointmentService()) -> getHelpAppointment();
			if($resultHelpAppointment['code'] != 0) {
				echo '<meta charset="utf-8"><script>alert("请今天先预约，才可提现!");window.location.href="/appointment";</script>';exit;
			}
		}

    	$resultCheckPayPassword = (new UserService()) -> checkPayPassword($post['pay_password']);
    	if($resultCheckPayPassword['code'] !== 0) {
    		echo '<meta charset="utf-8"><script>alert("' . $resultCheckPayPassword['message'] . '!");window.history.go(-1);</script>';exit;
    	}

		\think\Db::startTrans();
		try {
			$resultHelpGet = (new HelpGetService()) -> withdraw($post['money']);
	    	if($resultHelpGet['code'] !== 0) {
	    		throw new \Exception($resultHelpGet['message']);
	    	}

			$resultUserWallet['data']['user_wallet'] -> money -= $post['money'];
			$resultUserWallet['data']['user_wallet'] -> withdraw_position -= $post['money'];
			if(!$resultUserWallet['data']['user_wallet'] -> save()) {
				throw new \Exception('金额或提现额度扣除失败');
			}

			$user_name = \think\Session::get('user_name');
			$resultUserWalletLog = (new UserWalletLogService) -> log(3, 0, $post['money'], $user_name, '提现', 1, $user_name);
			if($resultUserWalletLog['code'] !== 0) {
				throw new \Exception($resultUserWalletLog['message']);
			}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();

			echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '!");window.history.go(-1);</script>';exit;
		}

		// 执行预约匹配
		//(new HelpAppointmentService()) -> matchHelpGetOrder();

    	echo '<meta charset="utf-8"><script>alert("' . $resultHelpGet['message'] . '!");window.location.href="/withdraw";</script>';exit;
    }

    public function confirmHelpGet() {
    	return json((new HelpGet()) -> confirmHelpGet($this -> request -> post('help_get_id')));
    }

    public function notConfirmHelpGet() {
    	return json((new HelpGet()) -> notConfirmHelpGet($this -> request -> post('help_get_id')));
    }

}